package com.wjf.accesscontrol.utils

import android.content.Context
import com.mingtech.sscarddirver.Reader
import com.wjf.accesscontrol.entity.UsbDevDesc

/**
 * @Description
 * @Author WuJianFeng
 * @Date 2023/12/15 9:54
 *
 */

class SdkUtils {

    companion object {
        val instance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { SdkUtils() }
    }

    private var mUsbDescList = ArrayList<UsbDevDesc>()
    private var usbPermission: UsbDevPermission? = null

    fun setUsbPermission(context: Context) {
        usbPermission = UsbDevPermission(context)

    }

    /**
     * 连接设备
     */
    fun connectDevice() {

        var st: Long = 0
        var device_fd = 0
        mUsbDescList.clear()
        val usbDeviceHashMap = usbPermission?.GetDeviceList()
        if (usbDeviceHashMap != null && usbDeviceHashMap.size > 0) {
            if (usbDeviceHashMap.isNotEmpty()) {
                for (device in usbDeviceHashMap.values) {
                    if ((0x10C4 == device.vendorId) || (0x23A4 == device.vendorId)) {
                        mUsbDescList.add(UsbDevDesc(device.vendorId, device.productId))
                    }
                }
            } else {
                ToastUtils.instance.show("当前未找到USB设备", 0)
                return
            }
        }

        if (mUsbDescList.isEmpty()) {
            ToastUtils.instance.show("未找到当前开发包支持的USB设备")
            return
        }
        var usbDev: UsbDevDesc? = null


        val it: Iterator<UsbDevDesc> = mUsbDescList.iterator()
        while (it.hasNext()) {
            if (usbPermission == null){
                return
            }
            usbDev = it.next()
            if (usbDev != null) {
                device_fd = usbPermission!!.getUsbFileDescriptor(usbDev.usbVid, usbDev.usbPid)
                if (device_fd < 0) {
                    device_fd = usbPermission!!.getUsbFileDescriptor(usbDev.usbVid, usbDev.usbPid)
                    if (device_fd < 0) {
                        val strShow = String.format("获取 USB[Vid:0x%02x,Pid:0x%02x]设备 描述符失败", usbDev.usbVid, usbDev.usbPid)
                        ToastUtils.instance.show(strShow)
                        return
                    }
                }
            } else {
                ToastUtils.instance.show("未找到当前开发包支持的USB设备")
                return
            }
        }
        st = Reader.iOpenUsbDevice(
            usbDev!!.usbVid,
            usbDev.usbPid,
            device_fd,
            usbPermission!!.usbDevPath.toByteArray()
        )

        if (st > 0) {
            ToastUtils.instance.show("打开USB端口成功", 1)
        } else {
            ToastUtils.instance.show("打开USB端口失败,st=$st", 0)
        }
    }

    /**
     * 断开连接
     */
    fun disconnected(){

        val st = Reader.iCloseDevice()
        if (st == 0L) {
            ToastUtils.instance.show("关闭端口成功")
        } else {
            ToastUtils.instance.show("关闭端口失败,ret=$st")
        }
    }
}